# -*- coding: utf-8 -*-
# Tubedl 2.0 QT Arabirimi
 # Copyright (C) 2007 - 2008
 # Oğuzhan Eroğlu (oguzhan@oguzhaneroglu.com)
 # Mk18(mertk18@gmail.com)
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.

 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.

import re
import os
from PyQt4 import QtCore, QtGui, QtNetwork
import urllib2
import sys
from ui_tubedl import Ui_TubedlWindow
import video_api

destek = ("youtube.com", "izlesene.com", "vidivodo.com")

class cevir(QtCore.QThread):
	def __init__(self):
		QtCore.QThread.__init__(self)
		self.visim = ""
		self.uzanti = ""
	def cevir(self, yerLine):
		os.chdir(yerLine)
		os.system("ffmpeg -i '%s.fla' '%s.%s'" % (self.visim, self.visim, self.uzanti))

class mainWindow(QtGui.QMainWindow, Ui_TubedlWindow, video_api.API):
	def __init__(self):
		QtGui.QMainWindow.__init__(self)
		video_api.API.__init__(self)
		self.setupUi(self)
		self.video_adres = ""
		self.url_dl = ""
		self.url_flv_ = ""
		self.url_flv = ""
		self.destek = destek
		self.garguman = ""
		self.cevir = cevir()
		self.video_dosya = ""

	def cevirmeyehazirla(self, uzanti):
		self.statusBar.showMessage(u"Video çevriliyor...")
		self.cevir.uzanti = uzanti
		self.cevir.visim = str(self.kisimLine.text())
		self.cevir.cevir(str(self.yerLine.text()))
		self.statusBar.showMessage("Çevirme tamamlandı.")

	def bitti(self, a):
		self.url_read = self.http.readAll()
		exec("self.url_dl = self.%s(self.url_read)" % self.garguman.replace(".", "_"))
		self.url_flv = re.compile("/.*").findall(str(self.url_dl.replace("//", "--")))[0]
		self.indir(self.garguman_, self.url_flv)

	def bitti_flv(self, a):
		if self.http is None:
			return 0
		self.http.close()
		if self.aviButton.isChecked():
			self.cevirmeyehazirla("avi")
		if self.mp3Button.isChecked():
			self.cevirmeyehazirla("mp3")
		if self.cevirmeButton.isChecked():
			pass
		self.statusBar.showMessage(u"İndirme tamamlandı!"),

	def read(self, site, adres):
		self.http = QtNetwork.QHttp(site)
		self.http.get(adres)
		QtCore.QObject.connect(self.http, QtCore.SIGNAL("done(bool)"), self.bitti)

	def cozumle(self, video_adres):
		self.statusBar.showMessage(u"Adres çözümleniyor...")
		self.garguman = re.compile(str("|".join(self.destek))).findall(video_adres)[0]
		self.garguman_ = "www." + self.garguman
		self.adres = re.compile("/.*").findall(video_adres.replace("//", "--"))[0]
		self.read(self.garguman_, self.adres)

	def setbar(self, value, max):
		self.statusBar.showMessage(u"İndiriliyor (toplam boyut: %smb)" % str((max / 1024) / 1024))
		self.progressBar.setMaximum(max)
		self.progressBar.setValue(value)

	def indir(self, adres, flv_adres):
		self.video_dosya = QtCore.QFile(str("%s%s.flv" % (str(self.yerLine.text()), str(self.kisimLine.text()))))
		self.tadres = urllib2.urlopen(str(self.url_dl.replace("--", "//"))).geturl()
		self.tadres_url = re.compile("--(.*?)/.").findall(self.tadres.replace("//", "--"))[0]
		self.tadres_id = re.compile("/.*").findall(self.tadres.replace("//", "--"))[0]
		self.http = QtNetwork.QHttp(self.tadres_url)
		QtCore.QObject.connect(self.http, QtCore.SIGNAL("dataReadProgress(int,int)"), self.setbar)
		QtCore.QObject.connect(self.http, QtCore.SIGNAL("done(bool)"), self.bitti_flv)
		self.http.get(self.tadres_id, self.video_dosya)

	@QtCore.pyqtSignature("bool")
	def on_indirButton_clicked(self):
		self.kdosya_adi = "%s%s.avi" % (str(self.yerLine.text()), str(self.kisimLine.text()))
		self.kdosya_adi2 = "%s%s.mp3" % (str(self.yerLine.text()), str(self.kisimLine.text()))
		self.kdosya_adi3 = "%s%s.flv" % (str(self.yerLine.text()), str(self.kisimLine.text()))
		try:
			if (os.path.exists(self.kdosya_adi)) or (os.path.exists(self.kdosya_adi2)) or (os.path.exists(self.kdosya_adi3)):
				QtGui.QMessageBox.critical(self, u"Hata!", u"Belirtilen dosya zaten var.")
			else:
				if (str(self.adresLine.text()).__len__() == 0) or (str(self.yerLine.text()).__len__() == 0) or (str(self.kisimLine.text()).__len__() == 0):
					print "..."
					QtGui.QMessageBox.critical(self, u"Hata!", u"Eksik bilgi, tüm alanları doldurun.")
				else:
					self.cozumle(str(self.adresLine.text()))
		except:
			pass

	@QtCore.pyqtSignature("bool")
	def on_yerButton_clicked(self):
		self.yerb = QtGui.QFileDialog.getExistingDirectory(self, u"Kayıt yerini seçin", str(os.environ["HOME"]))
		self.yerLine.setText(self.yerb)

	@QtCore.pyqtSignature("bool")
	def on_durdurButton_clicked(self):
		self.http.abort()

	@QtCore.pyqtSignature("bool")
	def on_THakkinda_triggered(self):
		QtGui.QMessageBox.about(self, u"Tubedl Hakkında", u"Geliştiriciler:\n Oğuzhan Eroğlu (oguzhan@oguzhaneroglu.com)\n Mk18 (mertk18@gmail.com)\n Tubedl GPL ile lisanslanmıştır..\nProje sayfası: http://tubedl.googlecode.com/")

	@QtCore.pyqtSignature("bool")
	def on_actionQT_Hakk_nda_triggered(self):
		QtGui.QMessageBox.aboutQt(self)

	@QtCore.pyqtSignature("bool")
	def on_actionDesteklenen_Siteler_triggered(self):
		QtGui.QMessageBox.information(self, "Siteler", u"Tubedl aşağıdaki sitelerden download yapabilir:\n%s" % ", ".join(self.destek))

	@QtCore.pyqtSignature("bool")
	def on_action_k_triggered(self):
		sys.exit()

app = QtGui.QApplication(sys.argv)
mw = mainWindow()
mw.show()
app.exec_()